package com.dm0858.bianmin.ui.activity;

import android.content.Intent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.model.entity.NewsRecord;
import com.dm0858.bianmin.model.entity.NormalListData;
import com.dm0858.bianmin.model.entity.lanmu;
import com.dm0858.bianmin.model.event.TabRefreshCompletedEvent;
import com.dm0858.bianmin.model.event.TabRefreshEvent;
import com.dm0858.bianmin.model.response.NormalResponse;
import com.dm0858.bianmin.ui.adapter.NormalListAdapter;
import com.dm0858.bianmin.ui.base.BaseActivity;
import com.dm0858.bianmin.ui.presenter.NormalListPresenter;
import com.dm0858.bianmin.utils.ListUtils;
import com.dm0858.bianmin.utils.NetWorkUtils;
import com.dm0858.bianmin.utils.NormalListRecordHelper;
import com.dm0858.bianmin.utils.UIUtils;
import com.dm0858.bianmin.view.INormalListView;
import com.chaychan.library.BottomBarItem;
import com.dm0858.uikit.TipView;
import com.dm0858.uikit.powerfulrecyclerview.PowerfulRecyclerView;
import com.dm0858.uikit.refreshlayout.BGANormalRefreshViewHolder;
import com.dm0858.uikit.refreshlayout.BGARefreshLayout;
import com.github.nukc.stateview.StateView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by yelvqing on 2017/11/16.
 */

public class NormalListActivity extends BaseActivity<NormalListPresenter> implements INormalListView, BGARefreshLayout.BGARefreshLayoutDelegate, BaseQuickAdapter.RequestLoadMoreListener {

    @Bind(R.id.iv_back)
    ImageView mIvBack;

    @Bind(R.id.normal_listtitle)
    TextView mtitle;

    @Bind(R.id.tip_view)
    TipView mTipView;

    @Bind(R.id.normalfl_content)
    FrameLayout mFlContent;

    @Bind(R.id.normalrefresh_layout)
    BGARefreshLayout mRefreshLayout;



    @Bind(R.id.normalrv_news)
    PowerfulRecyclerView mRvNews;

    @Override
    protected NormalListPresenter createPresenter() {
        return new NormalListPresenter(this);
    }


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_normallist;
    }

    //新闻记录
    private NewsRecord mNewsRecord;

    private List<NormalListData> mNewsList = new ArrayList<>();
    protected BaseQuickAdapter mNewsAdapter;

    /**
     * 是否是点击底部标签进行刷新的标识
     */
    private boolean isClickTabRefreshing;
    private RotateAnimation mRotateAnimation;
    private Gson mGson = new Gson();


    public static final String SECIONID = "AA";
    public static final String AREA = "AREA";
    public static final String LAT = "LAT";
    public static final String LNG = "LNG";


    protected String mSectionId;
    protected String mSectionName;

    protected String mArea;
    protected String mlat;
    protected String mLng;
    @Override
    public void initView() {

        Intent intent = getIntent();

        int aa=intent.getIntExtra(SECIONID, 0);
        mSectionId = Integer.toString(aa);

        mArea = intent.getStringExtra(AREA);
        mlat = intent.getStringExtra(LAT);
        mLng = intent.getStringExtra(LNG);

        String luanmu_str = "[{\"id\":\"5\",\"name\":\"\\u5f00\\u9501\\u6362\\u9501\"},{\"id\":\"20\",\"name\":\"\\u4e94\\u91d1\\u5efa\\u6750\"},{\"id\":\"7\",\"name\":\"\\u5bb6\\u7535\\u7ef4\\u4fee\"},{\"id\":\"30\",\"name\":\"\\u7535\\u8111\\u7ef4\\u4fee\"},{\"id\":\"8\",\"name\":\"\\u71c3\\u5177\\u7ef4\\u4fee\"},{\"id\":\"6\",\"name\":\"\\u7ba1\\u9053\\u758f\\u901a\"},{\"id\":\"12\",\"name\":\"\\u6c34\\u7535\\u7ef4\\u4fee\"},{\"id\":\"11\",\"name\":\"\\u5377\\u95e8\\u7ef4\\u4fee\"},{\"id\":\"10\",\"name\":\"\\u5bb6\\u653f\\u670d\\u52a1\"},{\"id\":\"25\",\"name\":\"\\u642c\\u5bb6\\u670d\\u52a1\"},{\"id\":\"9\",\"name\":\"\\u79df\\u623f\\u4e70\\u623f\"},{\"id\":\"17\",\"name\":\"\\u5ba0\\u7269\\u533b\\u7597\"},{\"id\":\"32\",\"name\":\"\\u5bb6\\u88c5\\u7ef4\\u4fee\"},{\"id\":\"16\",\"name\":\"\\u5e73\\u5b89\\u4ee3\\u9a7e\"},{\"id\":\"29\",\"name\":\"\\u540c\\u57ce\\u8dd1\\u817f\"},{\"id\":\"31\",\"name\":\"\\u540c\\u57ce\\u5916\\u5356\"},{\"id\":\"37\",\"name\":\"\\u6559\\u80b2\\u57f9\\u8bad\"},{\"id\":\"15\",\"name\":\"\\u62a5\\u8b66\\u6c42\\u52a9\"},{\"id\":\"34\",\"name\":\"\\u4e8c\\u624b\\u6c7d\\u8f66\"},{\"id\":\"19\",\"name\":\"\\u6c11\\u5fc3\\u8bba\\u575b\"},{\"id\":\"23\",\"name\":\"\\u624b\\u673a\\u8ba2\\u7968\"},{\"id\":\"46\",\"name\":\"\\u6279\\u53d1\\u91c7\\u8d2d\"},{\"id\":\"47\",\"name\":\"\\u8d85\\u5e02\\u767e\\u8d27\"},{\"id\":\"48\",\"name\":\"\\u65c5\\u6e38\\u8d2d\\u7269\\u8857\"},{\"id\":\"49\",\"name\":\"\\u751f\\u6d3b\\u4e07\\u82b1\\u7b52\"},{\"id\":\"50\",\"name\":\"\\u73a9\\u8f6c\\u57ce\\u5e02\"},{\"id\":\"45\",\"name\":\"\\u5bb6\\u7535\\u706f\\u9970\"},{\"id\":\"44\",\"name\":\"\\u8863\\u978b\\u5b9a\\u5236\"},{\"id\":\"43\",\"name\":\"\\u672c\\u5730\\u7279\\u4ea7\"},{\"id\":\"42\",\"name\":\"\\u7f8e\\u5bb9\\u5065\\u8eab\"},{\"id\":\"41\",\"name\":\"\\u5a5a\\u5e86\\u6444\\u5f71\"},{\"id\":\"40\",\"name\":\"\\u7528\\u9910\\u4f4f\\u5bbf\"},{\"id\":\"39\",\"name\":\"\\u836f\\u5e97\\u533b\\u7597\"},{\"id\":\"38\",\"name\":\"\\u9001\\u6876\\u88c5\\u6c34\"},{\"id\":\"51\",\"name\":\"\\u8f66\\u8f86\\u670d\\u52a1\"}]";
        Gson gson = new Gson();
        Type type = new TypeToken<List<lanmu>>() {
        }.getType();
        List<lanmu> luanmu = gson.fromJson(luanmu_str, type);
        KLog.e("sectionid="+mSectionId);
        KLog.e("66="+luanmu.get(0).name);
        for(int i = 0 ; i < luanmu.size() ; i++) {

            if (Integer.parseInt(mSectionId)>= 38) {
                lanmu lanmu = luanmu.get(i);
                if(mSectionId.equals(lanmu.id))
                {

                    mSectionId = luanmu.get(i).id.toString();
                    mSectionName = luanmu.get(i).name.toString();
                    KLog.e("66="+mSectionId);
                    break;
                }
            }else {
                if(Integer.parseInt(mSectionId)==i)
                {

                    mSectionId = luanmu.get(i).id.toString();
                    mSectionName = luanmu.get(i).name.toString();
                    KLog.e("66="+mSectionId);
                    break;
                }
            }

        }

        mtitle.setText(mSectionName);
        mStateView = StateView.inject(mFlContent);
        mStateView.setLoadingResource(R.layout.page_loading);
        mStateView.setRetryResource(R.layout.page_net_error);

        mRefreshLayout.setDelegate(this);

        mRvNews.setLayoutManager(new GridLayoutManager(this, 1));
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGANormalRefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, false);
        // 设置下拉刷新
        refreshViewHolder.setRefreshViewBackgroundColorRes(R.color.pull_refresh_bg);//背景色
        refreshViewHolder.setPullDownRefreshText(UIUtils.getString(R.string.refresh_pull_down_text));//下拉的提示文字
        refreshViewHolder.setReleaseRefreshText(UIUtils.getString(R.string.refresh_release_text));//松开的提示文字
        refreshViewHolder.setRefreshingText(UIUtils.getString(R.string.refresh_ing_text));//刷新中的提示文字


        // 设置下拉刷新和上拉加载更多的风格
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);
        mRefreshLayout.shouldHandleRecyclerViewLoadingMore(mRvNews);

    }

    @Override
    public void initData() {



    }

    @Override
    public void initListener() {
        mNewsAdapter = new NormalListAdapter(this, mNewsList);
        mRvNews.setAdapter(mNewsAdapter);

        mNewsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {


                Intent intent = new Intent(getApplication(), ShangJiaActivity.class);
                intent.putExtra(ShangJiaActivity.id, mNewsList.get(position).id);
                intent.putExtra("lat", mNewsList.get(position).lat);
                intent.putExtra("lng", mNewsList.get(position).lng);
                intent.putExtra("addr", mNewsList.get(position).addr);
                startActivity(intent);

            }
        });


        mNewsAdapter.setEnableLoadMore(true);
        mNewsAdapter.setOnLoadMoreListener(this, mRvNews);


        loadData();

    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (!NetWorkUtils.isNetworkAvailable(this)) {
            //网络不可用弹出提示
            mTipView.show();
            if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
                mRefreshLayout.endRefreshing();
            }
            return;
        }
        mPresenter.getNormalList(mSectionId,mArea,mlat,mLng);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        // BGARefresh的加载更多，不处理,使用到的是BaseRecyclerViewAdapterHelper的加载更多
        return false;
    }

    @Override
    public void onGetNormalListSuccess(NormalResponse nomallist) {

       // mTipView.show("加载成功");

        KLog.e("ekod="+nomallist.data);

        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新
        postRefreshCompletedEvent();//发送加载完成的事件

        //如果是第一次获取数据
        if (ListUtils.isEmpty(mNewsList)) {
            if (ListUtils.isEmpty(nomallist.data)) {
                //获取不到数据,显示空布局
                mStateView.showEmpty();
                return;
            }
            mStateView.showContent();//显示内容
        }

        if (ListUtils.isEmpty(nomallist.data)) {
            //已经获取不到新闻了，处理出现获取不到新闻的情况
            UIUtils.showToast(UIUtils.getString(R.string.no_news_now));
            return;
        }




        mNewsList.clear();
        mNewsList.addAll(0, nomallist.data);
        mNewsAdapter.notifyDataSetChanged();

        mTipView.show("加载成功");

        //保存到数据库
        NormalListRecordHelper.save( mGson.toJson(nomallist.data));

    }

    protected void loadData() {
        mStateView.showLoading();

        mNewsRecord = new NewsRecord();//创建一个没有数据的对象
        mPresenter.getNormalList(mSectionId,mArea,mlat,mLng);
        /*
        //查找该频道的最后一组记录
        mNewsRecord = NormalListRecordHelper.getLastNewsRecord();
        if (mNewsRecord == null) {
            //找不到记录，拉取网络数据
            mNewsRecord = new NewsRecord();//创建一个没有数据的对象
            mPresenter.getNormalList(mSectionId);
            return;
        }

        //找到最后一组记录，转换成新闻集合并展示
        List<NormalListData> newsList = NormalListRecordHelper.convertToNewsList(mNewsRecord.getJson());
        mNewsList.clear();

        mNewsList.addAll(newsList);//添加到集合中
        mNewsAdapter.notifyDataSetChanged();//刷新adapter

        mStateView.showContent();//显示内容
        mRefreshLayout.beginRefreshing();
        //判断时间是否超过10分钟，如果是则自动刷新
        if (mNewsRecord.getTime() - System.currentTimeMillis() == 10 * 60 * 100) {
            mRefreshLayout.beginRefreshing();
        }*/
    }




    @Override
    public void onError() {
        mTipView.show();//弹出提示

        if (ListUtils.isEmpty(mNewsList)) {
            //如果一开始进入没有数据
            mStateView.showRetry();//显示重试的布局
        }

        //收起刷新
        if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
            mRefreshLayout.endRefreshing();
        }
        postRefreshCompletedEvent();//发送加载完成的事件
       // mTipView.show();//弹出提示
    }

    private void postRefreshCompletedEvent() {
        if (isClickTabRefreshing) {
            //如果是点击底部刷新获取到数据的,发送加载完成的事件
            EventBus.getDefault().post(new TabRefreshCompletedEvent());
            isClickTabRefreshing = false;
        }
    }


    @Override
    public void onLoadMoreRequested() {
        // BaseRecyclerViewAdapterHelper的加载更多
        if (mNewsRecord.getPage() == 0 || mNewsRecord.getPage() == 1) {
            //如果记录的页数为0(即是创建的空记录)，或者页数为1(即已经是第一条记录了)
            //mRefreshLayout.endLoadingMore();//结束加载更多
            mNewsAdapter.loadMoreEnd();
            return;
        }

        NewsRecord preNewsRecord = NormalListRecordHelper.getPreNewsRecord(mNewsRecord.getPage());
        if (preNewsRecord == null) {
            // mRefreshLayout.endLoadingMore();//结束加载更多
            mNewsAdapter.loadMoreEnd();
            return;
        }

        mNewsRecord = preNewsRecord;

        long startTime = System.currentTimeMillis();

        List<NormalListData> newsList = NormalListRecordHelper.convertToNewsList(mNewsRecord.getJson());



        long endTime = System.currentTimeMillis();

        //由于是读取数据库，如果耗时不足1秒，则1秒后才收起加载更多
        if (endTime - startTime <= 1000) {
            UIUtils.postTaskDelay(new Runnable() {
                @Override
                public void run() {
                    mNewsAdapter.loadMoreComplete();
                    mNewsList.addAll(newsList);//添加到集合下面
                    mNewsAdapter.notifyDataSetChanged();//刷新adapter
                }
            }, (int) (1000 - (endTime - startTime)));
        }
    }

    /**
     * 接收到点击底部首页页签下拉刷新的事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(TabRefreshEvent event) {
        if (!NetWorkUtils.isNetworkAvailable(this)) {
            //网络不可用弹出提示
            mTipView.show();
            return;
        }

        isClickTabRefreshing = true;

        if (event.isHomeTab()) {
            //如果页签是首页，则换成就加载的图标并执行动画
            BottomBarItem bottomBarItem = event.getBottomBarItem();
            bottomBarItem.setIconSelectedResourceId(R.mipmap.tab_loading);//更换成加载图标
            bottomBarItem.setStatus(true);

            //播放旋转动画
            if (mRotateAnimation == null) {
                mRotateAnimation = new RotateAnimation(0, 360,
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                        0.5f);
                mRotateAnimation.setDuration(800);
                mRotateAnimation.setRepeatCount(-1);
            }
            ImageView bottomImageView = bottomBarItem.getImageView();
            bottomImageView.setAnimation(mRotateAnimation);
            bottomImageView.startAnimation(mRotateAnimation);//播放旋转动画
        }


        mRvNews.scrollToPosition(0);//滚动到顶部
        mRefreshLayout.beginRefreshing();//开始下拉刷新
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }
}
